package normal.栈.基于链表实现的栈;

import normal.链表.ListNode;

/**
 * 基于链表实现的栈
 *
 * @author ZhuYi
 * @create 2024/12/16 10:32
 */
public class LinkedListStack {
    private ListNode top;//栈顶
    private int size;//栈的长度

    LinkedListStack() {
        top = null;
        size = 0;
    }

    //入栈
    void push(ListNode node) {
        node.next = top;
        top = node;
        size++;
    }

    //出栈
    int pop() {
        if (empty()) throw new IndexOutOfBoundsException("栈为空");
        top = top.next;
        size--;
        return size();
    }

    //获取栈顶元素
    int peek() {
        if (empty()) throw new IndexOutOfBoundsException("栈为空");
        return top.val;
    }

    //栈是否为空
    boolean empty() {
        return size() == 0;
    }

    //获取栈的长度
    int size() {
        return size;
    }

    //组成数组并返回
    int[] toArray() {
        int[] arr = new int[size()];
        ListNode node = top;
        for (int i = size() - 1; i >= 0; i--) {
            arr[i] = node.val;
            node = node.next;
        }
        return arr;
    }
}
